package com.dao.impl;

import com.dao.RoleFunctionDAO;
import com.entity.Function;
import com.entity.MenuInfo;
import com.entity.RoleFunction;
import com.entity.RoleMenu;
import com.sys.utils.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 权限角色关系管理的数据访问类
 * 
 * @author xieqing
 * 
 */
public class RoleFunctionDaoImpl implements RoleFunctionDAO {


	/**
	 * 根据角色编号查询所属权限
	 * 
	 * @param roleId
	 *           
	 * @return
	 */
	public List<Function> getFunctionList(Integer roleId) {
		Connection con = null;
		PreparedStatement pre = null;
		ResultSet res = null;

		try {
			String sql = "SELECT *  FROM function WHERE id IN (SELECT function_id FROM role_function WHERE role_id=?) and mark=1 ";// and men_menu_id is not null ";
			con = DBUtils.getConnection();
			pre = con.prepareStatement(sql);
			pre.setInt(1, roleId);
			res = pre.executeQuery();
			List<Function> list = new ArrayList<Function>();
			while (res.next()) {
				Function function = new Function();
				function.setId(res.getInt("id"));
				function.setMark(res.getInt("mark"));
				function.setUrl(res.getString("url"));
				function.setName(res.getString("name"));
				list.add(function);
			}
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			DBUtils.close(con, pre, res);
		}

		return null;
	}

	@Override
	public boolean add(List<RoleFunction> list) {
		Connection con = null;
		PreparedStatement pre = null;
		PreparedStatement pre2 = null;
		try {
			String sql = "insert into role_function (function_id,role_id) values(?,?)";
			con = DBUtils.getConnection();
			// 关闭自动提交事物
			con.setAutoCommit(false);

			//先删除已经存在的
			String sql2 = "delete from role_function where role_id=?";
			pre2 = con.prepareStatement(sql2);
			pre2.setInt(1, list.get(0).getRoleId());
			pre2.executeUpdate();

			for (RoleFunction rf : list) {
				pre = con.prepareStatement(sql);
				pre.setInt(1, rf.getFunctionId());
				pre.setInt(2, rf.getRoleId());
				// 执行
				pre.executeUpdate();
			}

			con.commit();
			return true;

		} catch (Exception e) {
			try {
				con.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}finally{
			DBUtils.close(null, pre2);
			DBUtils.close(con, pre);
		}

		return false;
	}

}
